package com.cloud.apis.organization.service.impl;

import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.core.model.Dict;
import com.cloud.apis.core.model.PageData;
import com.cloud.apis.core.model.Post;
import com.cloud.apis.core.utils.PageInfoToPageDataConverterUtil;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.organization.db.dao.OrganizationMapper;
import com.cloud.apis.organization.db.dao.PostMapper;
import com.cloud.apis.organization.pojo.form.*;
import com.cloud.apis.organization.pojo.vo.OrganizationTreeVo;
import com.cloud.apis.organization.pojo.vo.PostInfoVo;
import com.cloud.apis.organization.pojo.vo.TransferInfoVo;
import com.cloud.apis.organization.service.IPostService;
import com.cloud.apis.user.db.dao.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 岗位API相关接口业务层实现
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/4/1
 */
@Slf4j
@Service
public class PostService implements IPostService {
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private OrganizationService organizationService;
    @Value("${custom-config.default-query-page-size}")
    private Integer defaultQueryPageSize;
    public PostService() {
        log.info("【PostService】");
    }

    @Override
    public ArrayList<Post> getPostByOrganizationId(Long id) {
        if (id == null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织id不能为空");
        }
        OrganizationTreeVo oTree = organizationService.getOrganizationTreeById(id);
        List<Long> allChildValues = getAllChildValues(oTree, id);
        return postMapper.selectPostByOrganizationId((ArrayList<Long>) allChildValues);
    }

    @Override
    public PageData<PostInfoVo> listPost(PostListForm form) {
        return listPage(form.getPageNum(),defaultQueryPageSize, form);
    }

    @Override
    public PageData<PostInfoVo> listPage(Integer pageNum, Integer pageSize, PostListForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<PostInfoVo> list = postMapper.list(form.getOrganizationId());
        PageInfo<PostInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PostInfoVo addPost(AddPostForm form) {
        if(organizationMapper.selectOrganizationById(form.getOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织不存在");
        }
        if (postMapper.selectPostByAbbreviation(form.getAbbreviation())!=null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该简称已存在");
        }
        int num = postMapper.insertPost(form);
        if (num==0){
            throw new CustomException(ServiceCode.ERROR_INSERT.getValue(), "添加岗位失败");
        }
        return postMapper.selectPostInfoById(form.getId());
    }

    @Override
    public void updatePost(UpdatePostForm form) {
        if (postMapper.selectPostById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "岗位不存在");
        }
        if(organizationMapper.getOrganizationById(form.getOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织不存在");
        }
        PostInfoVo post = postMapper.selectPostByAbbreviation(form.getAbbreviation());
        if(post!=null && !post.getId().equals(form.getId())){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该简称已存在");
        }
        int num = postMapper.updatePost(form);
        if (num==0){
            throw new CustomException(ServiceCode.ERROR_UPDATE.getValue(), "更新岗位失败");
        }
    }

    @Override
    public PostInfoVo getPostInfoById(Long id) {
        return postMapper.selectPostInfoById(id);
    }

    @Override
    public void setPostEnable(EnablePostForm form) {
        if(postMapper.selectPostById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "岗位不存在");
        }
        if(userMapper.selectUSerByPostId(form.getId())!=null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该岗位下存在用户，无法禁用");
        }
        int num = postMapper.setPostEnable(form);
        if (num==0){
            throw new CustomException(ServiceCode.ERROR_UPDATE.getValue(), "更新岗位失败");
        }
    }

    @Override
    public PageData<PostInfoVo> searchByName(Integer pageNum, Integer pageSize, SearchPostForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<PostInfoVo> list = postMapper.searchByName(form);
        PageInfo<PostInfoVo> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PageData<PostInfoVo> listSearchResult(SearchPostForm form) {
        return searchByName(form.getPageNum(), defaultQueryPageSize, form);
    }

    @Override
    public ArrayList<Post> listPostByOrganizationId(OrganizationIdForm form) {
        ArrayList<Long> list = new ArrayList<>();
        if(organizationMapper.selectOrganizationById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织不存在");
        }
        list.add(form.getId());
        return postMapper.selectPostByOrganizationId(list);
    }

    @Override
    public ArrayList<Post> listPostByOrganizationExpectUserId(OrganizationUserIdForm form) {
        if(userMapper.selectUserById(form.getUserId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "用户不存在");
        }
        if(organizationMapper.selectOrganizationById(form.getOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织不存在");
        }
        return postMapper.listPostByOrganizationExpectUserId(form.getOrganizationId(),form.getUserId());
    }

    @Override
    public TransferInfoVo setTransfer(TransferForm form) {
        if(userMapper.selectUserById(form.getTransferId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "用户不存在");
        }
        if(organizationMapper.selectOrganizationById(form.getNowOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织不存在");
        }
        if(postMapper.selectPostById(form.getNowPostId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "岗位不存在");
        }
        int num = postMapper.setTransfer(form);
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_UPDATE.getValue(), "更新岗位失败");
        }
        return postMapper.selectTransferInfoById(form.getTransferId());
    }

    @Override
    public void updateTransferInfo(UpdateTransferForm form) {
        if(userMapper.selectUserById(form.getTransferId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "用户不存在");
        }
        if(organizationMapper.selectOrganizationById(form.getNewOrganizationId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "组织不存在");
        }
        if(postMapper.selectPostById(form.getNewPostId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "岗位不存在");
        }
        int num  = postMapper.updateTransferInfo(form);
        if (num<=0){
            throw new CustomException(ServiceCode.ERROR_UPDATE.getValue(), "更新岗位失败");
        }
    }

    private List<Long> getAllChildValues(OrganizationTreeVo department, Long parentValue) {
        List<Long> childValues = new ArrayList<>();
        if (department.getValue().equals(parentValue)) {
            collectChildValues(department, childValues);
            return childValues;
        }
        for (OrganizationTreeVo child : department.getChildren()) {
            List<Long> foundValues = getAllChildValues(child, parentValue);
            if (!foundValues.isEmpty()) {
                childValues.addAll(foundValues);
            }
        }
        return childValues;
    }

    private void collectChildValues(OrganizationTreeVo department, List<Long> childValues) {
        childValues.add(department.getValue());
        for (OrganizationTreeVo child : department.getChildren()) {
            collectChildValues(child, childValues);
        }
    }

}
